/**
 * @description 根据code和parentCode转成树结构
 * @param list {Array} 需要转换的数据
 * */
function transformTree(list) {
    const tree = []
    for (let i = 0, len = list.length; i < len; i++) {
        if (!list[i].parentCode) {
            const item = queryChildren(list[i], list)
            tree.push(item)
        }
    }
    return tree
}

function queryChildren(parent, list) {
    const children = []
    for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].parentCode === parent.menuCode) {
            const item = queryChildren(list[i], list)
            children.push(item)
        }
    }
    if (children.length) {
        parent.children = children
    }
    return parent
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
function  handleTree(data, id, parentId, children) {
    let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
    };

    var childrenListMap = {};
    var nodeIds = {};
    var tree = [];

    for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
    }

    for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
            tree.push(d);
        }
    }

    for (let t of tree) {
        adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
            for (let c of o[config.childrenList]) {
                adaptToChildrenList(c);
            }
        }
    }

    function isMenuAlwaysShow(menus) {
        menus.forEach(item => {
            if (item.children && item.children.length > 0) {
                const show = item.children.some(v => !v.hidden)
                if (show) item.alwaysShow = true
                else {
                    item.alwaysShow = false
                    item.hidden = true
                }
                isMenuAlwaysShow(item.children)
            } else if (item.menuType === 'M') {
                item.alwaysShow = false
                item.hidden = true
            }
        })
    }

    isMenuAlwaysShow(tree)

    return tree;
}




module.exports = {transformTree, handleTree}
